//
//  PersonSetViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/8/6.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "PersonSetViewController.h"
#import "InfomationViewController.h"
#import <AFNetworking.h>
#import "DatePickerTool.h"
#import "SexPickerTool.h"

@interface PersonSetViewController ()<UITableViewDataSource, UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ChangeIntroDelegate>{
    UIImageView *_headImageView;//头像
    NSString *name;
    NSString *intro;
    NSMutableString *sex;
    NSMutableString *birth;
    UIImageView *_backgroundImage;
}

@property (nonatomic, strong) NSMutableArray *pic;
@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) UIImagePickerController *pickerController;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) DatePickerTool *datePicker;
@property (nonatomic, strong) SexPickerTool  *sexPicker;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UIView *backView2;

@end

@implementation PersonSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self getData];
    self.title = @"个人信息";
    _pic = [NSMutableArray array];
    _type = 0;
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = REXADECIMALCOLOR(@"#eeeeee");
    [self.view addSubview:self.tableView];
    
    UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49), SCREEN_WIDTH, ScreenX375(49))];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setBackgroundImage:[UIImage imageNamed:@"按钮背景"] forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.titleLabel.font = Kfont(18);
    [saveBtn addTarget:self action:@selector(updateInfo) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
    
    self.pickerController = [[UIImagePickerController alloc] init];
    self.pickerController.delegate = self;
    
    _sexPicker = [[SexPickerTool alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - ScreenX375(225), SCREEN_WIDTH, ScreenX375(225))];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelPicker)];
    
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    [_backView addGestureRecognizer:tap1];
    
     __weak __typeof(self)weakSelf = self;
    _sexPicker.callBlock = ^(NSString *pickData) {
        if (pickData) {
            self->sex = [pickData mutableCopy];
        }
        weakSelf.backView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    };
    
    _sexPicker.cancelBlock = ^{
        weakSelf.backView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    };
    
    [_backView addSubview:_sexPicker];
    [kKeyWindow addSubview:_backView];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelPicker)];
    
    _backView2 = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView2.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    [_backView2 addGestureRecognizer:tap2];
    
    _datePicker = [[DatePickerTool alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - ScreenX375(225), SCREEN_WIDTH, ScreenX375(225))];
    
    _datePicker.callBlock = ^(NSString *pickData) {
        if (pickData) {
            self->birth = [pickData mutableCopy];
        }
        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
        weakSelf.backView2.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    };
    
    _datePicker.cancelBlock = ^{
         weakSelf.backView2.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    };
    
    [_backView2 addSubview:_datePicker];
    [kKeyWindow addSubview:_backView2];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [self.backView removeFromSuperview];
    [self.backView2 removeFromSuperview];
}

-(void)updateInfo{
    NSMutableArray *image = [NSMutableArray array];
    [image addObject:_headImageView.image];
    if (_backgroundImage.image) {
        [image addObject:_backgroundImage.image];
    }
    [HttpManager uploadImageArr:image success:^(id successResponse) {
        self.pic = successResponse;
        [self upload];
    }];
}

- (void)upload {
    [HttpManager showWait];
    NSDictionary *parameter = @{@"id":kNSUDefaultReadKey(@"userId"),@"nickName":name,@"intro":intro,@"pic":[_pic objectAtIndex:0]};
    if (self.pic.count > 1) {
        parameter = @{@"id":kNSUDefaultReadKey(@"userId"),@"nickName":name,@"intro":intro,@"pic":[_pic objectAtIndex:0],@"background":[_pic objectAtIndex:1]};
    }
    
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/updateUserInfo",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *code = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([code isEqualToString:@"200"]) {
            [HttpManager showNoteMsg:@"上传成功"];
            NSString *pic = [self.pic objectAtIndex:0];
            kNSUDefaultSaveVauleAndKey(pic, @"pic");
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showNoteMsg:@"上传失败"];
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return 5;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *cellID = @"section0Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            if (!_headImageView) {
                _headImageView = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(56)) / 2, ScreenX375(30), ScreenX375(56), ScreenX375(56))];
                _headImageView.layer.masksToBounds = YES;
                [_headImageView.layer setCornerRadius:ScreenX375(28)];
                [cell addSubview:_headImageView];
            }
            if ([_dict[@"userInfo"][@"pic"] class] != [NSNull class]) {
                [_headImageView sd_setImageWithURL:[NSURL URLWithString:_dict[@"userInfo"][@"pic"]] placeholderImage:nil options:SDWebImageRetryFailed];
            }
            
            UIButton *changeBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(80)) / 2, ScreenX375(96), ScreenX375(80), ScreenX375(26))];
            changeBtn.backgroundColor = REXADECIMALCOLOR(@"#ffd100");
            changeBtn.layer.cornerRadius = ScreenX375(13);
            changeBtn.clipsToBounds = YES;
            [changeBtn setTitle:@"更换头像" forState:UIControlStateNormal];
            [changeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [changeBtn setBackgroundImage:[UIImage imageNamed:@"按钮背景"] forState:UIControlStateNormal];
            changeBtn.titleLabel.font = Kfont(15);
            [changeBtn addTarget:self action:@selector(changeImage) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:changeBtn];
        }
        
        return cell;
    }else if(indexPath.section == 1 && indexPath.row < 2){
        static NSString *cellID = @"section1Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = indexPath.row == 0 ? @"昵称":@"签名";
        cell.textLabel.textColor = FONTCOLOR_BLACK;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        
        
        cell.detailTextLabel.text = indexPath.row == 0 ? name:intro;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(47.5), ScreenX375(359), ScreenX375(0.5))];
        line.backgroundColor = REXADECIMALCOLOR(@"#dddddd");
        [cell addSubview:line];
        
        return cell;
    }else if (indexPath.row == 2){
        static NSString *cellID = @"section1Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"性别";
        cell.textLabel.textColor = FONTCOLOR_BLACK;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        
        
        cell.detailTextLabel.text = sex;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(47.5), ScreenX375(359), ScreenX375(0.5))];
        line.backgroundColor = REXADECIMALCOLOR(@"#dddddd");
        [cell addSubview:line];
        
        return cell;
    }else if (indexPath.row == 3){
        static NSString *cellID = @"section1Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"生日";
        cell.textLabel.textColor = FONTCOLOR_BLACK;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        
        
        cell.detailTextLabel.text = birth;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(16), ScreenX375(47.5), ScreenX375(359), ScreenX375(0.5))];
        line.backgroundColor = REXADECIMALCOLOR(@"#dddddd");
        [cell addSubview:line];
        
        return cell;
    }else{
        static NSString *cellID = @"section1Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"背景";
        cell.textLabel.textColor = FONTCOLOR_BLACK;
        cell.textLabel.font = [UIFont systemFontOfSize:15];

        _backgroundImage = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(288), ScreenX375(16), ScreenX375(40), ScreenX375(40))];
        if ([_dict[@"userInfo"][@"background"] class] != [NSNull class]) {
            [_backgroundImage sd_setImageWithURL:[NSURL URLWithString:_dict[@"userInfo"][@"background"]] placeholderImage:nil options:SDWebImageRetryFailed];
        }
        [cell addSubview:_backgroundImage];
        
        return cell;
    }
}

- (void)getData {
    NSDictionary *parameter = @{@"id":kNSUDefaultReadKey(@"userId")};
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/getUserInfo",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            self->name = successResponse[@"data"][@"userInfo"][@"nickName"];
            self->intro = successResponse[@"data"][@"userInfo"][@"intro"];
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return ScreenX375(129);
    }if (indexPath.section == 1 && indexPath.row == 4) {
        return ScreenX375(72);
    }else{
        return ScreenX375(50);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
    view.backgroundColor = REXADECIMALCOLOR(@"#eeeeee");
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            InfomationViewController *vc = [[InfomationViewController alloc] init];
            vc.changeIntroDelegate = self;
            vc.value = name;
            vc.type = @"0";
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 1) {
            InfomationViewController *vc = [[InfomationViewController alloc] init];
            vc.changeIntroDelegate = self;
            vc.value = intro;
            vc.type = @"1";
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.row == 2){
            if (_backView) {
                self.backView.frame = CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT);
            }
        }else if (indexPath.row == 3){
            if (_backView2) {
                self.backView2.frame = CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT);
            }
        }else if (indexPath.row == 4){
            _type = 1;
            [self changeImage];
        }
    }
}


- (void)changeImage {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *send = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        self.pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    UIAlertAction *get = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        self.pickerController.allowsEditing = YES;
        [self presentViewController:self.pickerController animated:YES completion:nil];
    }];
    
    [alert addAction:cancel];
    [alert addAction:send];
    [alert addAction:get];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)changeIntro:(NSString *)str withType:(NSString *)type {
    if ([type integerValue]) {
        intro = str;
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }else {
        name = str;
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:1]] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (_type == 0) {
        _headImageView.image = image;
    }else{
        _backgroundImage.image = image;
    }
    _type = 0;
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.pickerController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)cancelPicker{
    _backView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    _backView2.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
}

@end
